const fs = require('fs').promises;
const path = require('path');

const {
  ASE_KEY
} = require('./config.cjs')

const { createCipheriv, createDecipheriv } = require('crypto');

const convertCryptKey = (secret) => {
  const newSecret = Buffer.from([
      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  ]);
  secret = Buffer.from(secret);
  for (let i = 0; i < secret.length; i++) newSecret[i % 16] ^= secret[i];
  return newSecret;
}

const decrypt = (event, { target }) => {
  const secret = ASE_KEY
  const algorithm = 'aes-128-ecb';
  const key = convertCryptKey(secret);
  const iv = '';
  const decipher = createDecipheriv(algorithm, key, iv);
  let decrypted = decipher.update(target, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

const encrypt = (target, secret = ASE_KEY) => {
  if (!ASE_ON) {
    return target;
  }
  const algorithm = 'aes-128-ecb';
  const key = this.convertCryptKey(secret);
  const iv = '';
  const cipher = createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(target, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted.toUpperCase();
}

module.exports = { decrypt, encrypt }; 